from flask import request, jsonify
from src.pojo.user import User
from database.database import db

def register_user_routes(app):
    # 添加用户
    @app.route('/user', methods=['POST'])
    def add_user():
        data = request.get_json()
        user_id = data.get('user_id')
        user_name = data.get('user_name')
        user_password = data.get('user_password')
        user_jurisdiction = data.get('user_jurisdiction')

        # 检查必填字段
        if not user_id or not user_name or not user_password or user_jurisdiction is None:
            return jsonify({'code': 401, 'message': '缺少必要参数'}), 401

        # 检查用户是否已存在
        existing_user = User.query.filter_by(user_id=user_id).first()
        if existing_user:
            return jsonify({'code': 402, 'message': '用户ID已存在'}), 402
        
        # 检查用户名是否已存在
        existing_username = User.query.filter_by(user_name=user_name).first()
        if existing_username:
            return jsonify({'code': 403, 'message': '用户名已存在'}), 403

        # 创建新用户
        new_user = User(user_id=user_id, user_name=user_name, user_password=user_password, user_jurisdiction=user_jurisdiction)
        
        try:
            db.session.add(new_user)
            db.session.commit()
            return jsonify({'code': 200, 'message': '用户创建成功', 'data': new_user.to_dict()}), 200
        except Exception as e:
            db.session.rollback()
            return jsonify({'code': 500, 'message': '创建用户失败: ' + str(e)}), 500

    # 用户登录
    @app.route('/login', methods=['POST'])
    def login():
        data = request.get_json()
        user_name = data.get('user_name')
        user_password = data.get('user_password')

        # 检查必填字段
        if not user_name or not user_password:
            return jsonify({'code': 400, 'message': '用户名和密码不能为空'}), 400

        # 查找用户
        user = User.query.filter_by(user_name=user_name).first()
        if not user:
            return jsonify({'code': 404, 'message': '用户不存在'}), 404

        # 验证密码
        if user.user_password != user_password:
            return jsonify({'code': 401, 'message': '账号或密码错误'}), 401

        # 登录成功
        return jsonify({
            'code': 200, 
            'message': '登录成功', 
            'data': {
                'user_id': user.user_id,
                'user_name': user.user_name,
                'user_jurisdiction': user.user_jurisdiction
            }
        }), 200

    # 查询所有用户
    @app.route('/users', methods=['GET'])
    def get_users():
        try:
            users = User.query.all()
            users_list = [user.to_dict() for user in users]
            return jsonify({'code': 200, 'message': '查询成功', 'data': users_list}), 200
        except Exception as e:
            return jsonify({'code': 500, 'message': '查询失败: ' + str(e)}), 500

    # 根据ID查询用户
    @app.route('/user/<user_id>', methods=['GET'])
    def get_user(user_id):
        try:
            user = User.query.filter_by(user_id=user_id).first()
            if user:
                return jsonify({'code': 200, 'message': '查询成功', 'data': user.to_dict()}), 200
            else:
                return jsonify({'code': 404, 'message': '用户不存在'}), 404
        except Exception as e:
            return jsonify({'code': 500, 'message': '查询失败: ' + str(e)}), 500

    # 更新用户信息
    @app.route('/user/<user_id>', methods=['PUT'])
    def update_user(user_id):
        user = User.query.filter_by(user_id=user_id).first()
        if not user:
            return jsonify({'code': 404, 'message': '用户不存在'}), 404

        data = request.get_json()
        new_user_id = data.get('user_id')
        user_name = data.get('user_name')
        user_password = data.get('user_password')
        user_jurisdiction = data.get('user_jurisdiction')

        # 检查用户ID是否已存在（且不是当前用户）
        if new_user_id:
            existing_user = User.query.filter_by(user_id=new_user_id).first()
            if existing_user and existing_user.user_id != user_id:
                return jsonify({'code': 400, 'message': '用户ID已存在'}), 400
        
        # 检查用户名是否已存在（且不是当前用户）
        if user_name:
            existing_username = User.query.filter_by(user_name=user_name).first()
            if existing_username and existing_username.user_id != user_id:
                return jsonify({'code': 400, 'message': '用户名已存在'}), 400

        # 更新用户信息
        if new_user_id is not None:
            user.user_id = new_user_id
        if user_name is not None:
            user.user_name = user_name
        if user_password is not None:
            user.user_password = user_password
        if user_jurisdiction is not None:
            user.user_jurisdiction = user_jurisdiction

        try:
            db.session.commit()
            return jsonify({'code': 200, 'message': '用户更新成功', 'data': user.to_dict()}), 200
        except Exception as e:
            db.session.rollback()
            return jsonify({'code': 500, 'message': '更新用户失败: ' + str(e)}), 500

    # 删除用户
    @app.route('/user/<user_id>', methods=['DELETE'])
    def delete_user(user_id):
        user = User.query.filter_by(user_id=user_id).first()
        if not user:
            return jsonify({'code': 404, 'message': '用户不存在'}), 404

        try:
            db.session.delete(user)
            db.session.commit()
            return jsonify({'code': 200, 'message': '用户删除成功'}), 200
        except Exception as e:
            db.session.rollback()
            return jsonify({'code': 500, 'message': '删除用户失败: ' + str(e)}), 500